<template>
  <div class="pdf-viewer-container" :style="{ height: viewerHeight }">

    <!-- 调试按钮（开发时使用） -->
    <div v-if="false" class="debug-tools" style="position: absolute; top: 10px; right: 10px; z-index: 1000;">
      <el-button size="mini" @click="debugPdf">调试</el-button>
      <el-button size="mini" @click="forceReload">强制重载</el-button>
    </div>

    <!-- 加载中状态（使用v-show） -->
    <div v-show="pdfLoading" class="pdf-loading">
      <Loading size="40" color="#1989fa" class="loading-spinner" />
      <p class="loading-text">正在加载PDF文档...</p>
    </div>

    <!-- 错误状态（使用v-show） -->
    <div v-show="pdfError" class="pdf-error">
      <div class="error-icon">
        <Document size="48" color="#f56c6c" />
      </div>
      <p class="error-message">{{ errorMsg }}</p>
      <el-button
          type="primary"
          size="small"
          @click="reloadPdf"
      >
        重新加载
      </el-button>
    </div>

    <!-- PDF预览状态（使用v-show，确保Canvas始终存在） -->
    <div v-show="!pdfLoading && !pdfError" class="pdf-preview">
      <!-- 工具栏 -->
      <div class="pdf-toolbar">
        <el-button
            type="primary"
            size="small"
            @click="downloadPdf"
            :icon="Download"
            :disabled="!pdfLoaded"
        >
          下载PDF
        </el-button>
        <el-button
            type="text"
            size="small"
            @click="reloadPdf"
        >
          刷新
        </el-button>

        <div class="page-control">
          <el-button
              type="text"
              size="small"
              @click="goToPrevPage"
              :disabled="pageNum <= 1 || pdfLoading"
          >
            上一页
          </el-button>
          <span class="page-info">第{{ pageNum }}页 / 共{{ pageCount }}页</span>
          <el-button
              type="text"
              size="small"
              @click="goToNextPage"
              :disabled="pageNum >= pageCount || pdfLoading"
          >
            下一页
          </el-button>
        </div>
      </div>
      <!-- PDF内容区域（Canvas始终存在于DOM中） -->
      <div class="pdf-content">
        <canvas ref="pdfCanvasRef" class="pdf-canvas"></canvas>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { Document, Download, Loading } from '@element-plus/icons-vue'
import * as pdfjsLib from 'pdfjs-dist'

// 组件Props定义
const props = defineProps<{
  pdfUrl: string // PDF地址（必填）
  fileName?: string // 下载文件名（可选）
  height?: string | number // 组件高度（可选）
  scale?: number // PDF缩放比例（可选，默认1.5）
}>()

// 组件事件定义
const emit = defineEmits<{
  (e: 'download-success'): void
  (e: 'download-fail', error: Error): void
  (e: 'load-success'): void
  (e: 'load-fail', error: Error): void
}>()

// 状态管理
const pdfLoading = ref(false)
const pdfError = ref(false)
const pdfLoaded = ref(false) // 标记文档是否加载成功（获取到总页数）
const errorMsg = ref('')
const viewerHeight = ref<string | number>('600px')
const pageNum = ref(1) // 当前页码
const pageCount = ref(0) // 总页数
const scale = ref(props.scale || 1.5) // 缩放比例
const pdfConfig = ref<{
  url: string
  cMapPacked: boolean
  cMapUrl: string
} | null>(null)

// 核心优化1：用 Vue ref 绑定 Canvas 元素（替代 document.getElementById）
const pdfCanvasRef = ref<HTMLCanvasElement | null>(null)
// 核心优化2：防抖标记，防止频繁渲染
const renderDebounce = ref(false)

// 核心修复：使用 CDN 加载 Worker（避免本地 Worker 导入问题）
pdfjsLib.GlobalWorkerOptions.workerSrc = `../public/pdf.worker.min.js`

/**
 * 初始化PDF配置 + 获取总页数
 */
const loadPdf = async () => {
  console.log('🚀 开始加载PDF，URL:', props.pdfUrl)

  if (!props.pdfUrl) {
    pdfError.value = true
    pdfLoaded.value = false
    errorMsg.value = 'PDF地址不能为空'
    ElMessage.error('PDF地址不能为空')
    return
  }

  pdfLoading.value = true
  pdfError.value = false

  try {
    console.log('📥 开始获取PDF文档...')

    // 关键修改：等待DOM更新，确保Canvas元素已渲染
    await nextTick()

    // 检查Canvas元素是否存在
    if (!pdfCanvasRef.value) {
      throw new Error('Canvas元素未准备好，请稍后重试')
    }

    // 简化配置，直接使用URL
    const loadingTask = pdfjsLib.getDocument({
      url: props.pdfUrl,
      // 移除不必要的配置
    })

    // 添加进度监听
    loadingTask.onProgress = (progress :any) => {
      console.log(`📊 加载进度: ${progress.loaded}/${progress.total}`)
    }

    const pdfDoc = await loadingTask.promise
    console.log('✅ PDF文档加载成功，总页数:', pdfDoc.numPages)

    pageCount.value = pdfDoc.numPages
    pdfLoaded.value = true
    emit('load-success')

    // 渲染第一页
    await renderPage(pageNum.value)

  } catch (error) {
    console.error('❌ PDF加载失败:', error)
    const err = error as Error
    pdfError.value = true
    pdfLoaded.value = false

    if (err.name === 'InvalidPDFException') {
      errorMsg.value = '无效的PDF文件格式'
    } else if (err.message.includes('404')) {
      errorMsg.value = 'PDF文件不存在 (404)'
    } else if (err.message.includes('CORS')) {
      errorMsg.value = '跨域限制，请联系后端配置CORS'
    } else {
      errorMsg.value = `加载失败: ${err.message}`
    }

    emit('load-fail', err)
    ElMessage.error('PDF加载失败')
  } finally {
    pdfLoading.value = false
  }
}

/**
 * 优化后的 PDF 渲染方法
 */
const renderPage = async (num: number, forceRender = false) => {
  if (renderDebounce.value && !forceRender) {
    console.log('⏳ 跳过渲染：防抖中')
    return
  }

  // 增加Canvas元素检查和等待
  if (!pdfCanvasRef.value) {
    console.log('⏳ 等待Canvas元素准备...')
    await nextTick() // 等待DOM更新
    if (!pdfCanvasRef.value) {
      throw new Error('Canvas元素未找到 - ref绑定失败')
    }
  }

  renderDebounce.value = true
  pdfLoading.value = true

  try {
    console.log(`🎨 开始渲染第${num}页...`)

    // 等待 Vue DOM 更新完成
    await nextTick()

    const canvas = pdfCanvasRef.value
    if (!canvas) {
      throw new Error('Canvas元素未找到 - ref绑定失败')
    }

    console.log('🖼️ Canvas元素状态:', {
      width: canvas.width,
      height: canvas.height,
      clientWidth: canvas.clientWidth,
      clientHeight: canvas.clientHeight,
      offsetWidth: canvas.offsetWidth,
      offsetHeight: canvas.offsetHeight
    })

    const context = canvas.getContext('2d')
    if (!context) {
      throw new Error('浏览器不支持Canvas 2D上下文')
    }

    // 清空画布
    context.clearRect(0, 0, canvas.width, canvas.height)

    console.log('📚 加载PDF文档...')
    // 重新加载PDF文档（避免缓存问题）
    const pdfDoc = await pdfjsLib.getDocument(props.pdfUrl).promise
    const page = await pdfDoc.getPage(num)

    // 计算视图尺寸
    const viewport = page.getViewport({ scale: scale.value })
    console.log(`📐 视图尺寸: ${viewport.width} x ${viewport.height}`)

    // 设置画布物理尺寸
    canvas.width = viewport.width
    canvas.height = viewport.height

    // 设置画布CSS尺寸（响应式）
    canvas.style.width = '100%'
    canvas.style.height = 'auto'
    canvas.style.maxWidth = `${viewport.width}px`

    console.log(`🔄 设置画布尺寸: ${canvas.width} x ${canvas.height}`)

    // 渲染页面
    console.log('🖌️ 开始渲染操作...')
    const renderContext = {
      canvasContext: context,
      viewport: viewport
    }

    await page.render(renderContext).promise

    // 验证渲染结果
    const imageData = context.getImageData(0, 0, 10, 10) // 检查左上角10x10像素
    const hasContent = imageData.data.some(value => value !== 0)
    console.log('🔍 渲染验证:', hasContent ? '有内容' : '可能空白')

    pageNum.value = num
    console.log(`✅ 第${num}页渲染完成`)

  } catch (error) {
    console.error(`❌ 第${num}页渲染失败:`, error)
    const err = error as Error

    if (err.message.includes('Invalid page')) {
      ElMessage.error(`第${num}页不存在`)
    } else {
      ElMessage.error(`渲染失败: ${err.message}`)
    }
  } finally {
    renderDebounce.value = false
    pdfLoading.value = false
  }
}

// 添加调试方法
const debugPdf = () => {
  console.group('🔧 PDF组件调试信息')
  console.log('PDF URL:', props.pdfUrl)
  console.log('Canvas Ref:', pdfCanvasRef.value)
  console.log('Canvas 尺寸:', pdfCanvasRef.value ? {
    width: pdfCanvasRef.value.width,
    height: pdfCanvasRef.value.height,
    style: {
      width: pdfCanvasRef.value.style.width,
      height: pdfCanvasRef.value.style.height
    }
  } : '未找到')
  console.log('状态:', {
    loading: pdfLoading.value,
    error: pdfError.value,
    loaded: pdfLoaded.value,
    page: `${pageNum.value}/${pageCount.value}`,
    scale: scale.value
  })
  console.groupEnd()
}

// 在关键位置调用调试
onMounted(() => {
  viewerHeight.value = props.height || '600px'
  // 延迟执行调试，确保DOM已渲染
  setTimeout(() => {
    debugPdf()
  }, 100)
})

/**
 * 重新加载PDF（优化：强制渲染，重置画布）
 */
const reloadPdf = () => {
  // 重置画布尺寸（避免残留）
  if (pdfCanvasRef.value) {
    const canvas = pdfCanvasRef.value
    const context = canvas.getContext('2d')
    if (context) {
      context.clearRect(0, 0, canvas.width, canvas.height)
      canvas.width = 0
      canvas.height = 0
    }
  }
  pageNum.value = 1
  pdfError.value = false
  errorMsg.value = ''
  loadPdf()
}

/**
 * 下载PDF
 */
const downloadPdf = () => {
  if (!props.pdfUrl) {
    ElMessage.warning('无PDF下载地址')
    return
  }

  try {
    const link = document.createElement('a')
    link.href = props.pdfUrl
    link.download = props.fileName || `PDF文档_${new Date().getTime()}.pdf`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('下载已开始')
    emit('download-success')
  } catch (error) {
    const err = error as Error
    ElMessage.error('下载失败：' + err.message)
    emit('download-fail', err)
  }
}

/**
 * 上一页（优化：增加防抖处理）
 */
const goToPrevPage = () => {
  if (pageNum.value > 1 && !renderDebounce.value) {
    pageNum.value--
    renderPage(pageNum.value)
  }
}

/**
 * 下一页（优化：增加防抖处理）
 */
const goToNextPage = () => {
  if (pageNum.value < pageCount.value && !renderDebounce.value) {
    pageNum.value++
    renderPage(pageNum.value)
  }
}

// 组件挂载时初始化
onMounted(() => {
  viewerHeight.value = props.height || '600px'
})

// 监听高度变化
watch(() => props.height, (newVal) => {
  if (newVal) {
    viewerHeight.value = newVal
  }
})

// 监听PDF地址变化，重新加载
watch(() => props.pdfUrl, (newUrl) => {
  if (newUrl) {
    pdfError.value = false
    errorMsg.value = ''
    // 等待 DOM 更新后再加载
    nextTick(() => {
      reloadPdf()
    })
  }
}, { immediate: true })

// 监听缩放比例变化（优化：增加防抖）
watch(scale, () => {
  if (pdfConfig.value && !renderDebounce.value) {
    renderPage(pageNum.value, true) // 强制渲染，跳过防抖
  }
})

// 添加强制重载方法
const forceReload = () => {
  console.log('🔄 强制重载PDF')
  // 清除可能的缓存
  if (pdfCanvasRef.value) {
    const canvas = pdfCanvasRef.value
    const ctx = canvas.getContext('2d')
    if (ctx) {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
    }
    canvas.width = 0
    canvas.height = 0
  }

  // 重置状态
  pageNum.value = 1
  pageCount.value = 0
  pdfLoaded.value = false
  pdfError.value = false
  errorMsg.value = ''

  // 重新加载
  loadPdf()
}

</script>

<style scoped>
.pdf-viewer-container {
  position: relative;
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #eee;
  box-sizing: border-box;
}

.pdf-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #fafafa;
}

/* 加载图标旋转动画 */
.loading-spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading-text {
  margin-top: 16px;
  color: #666;
  font-size: 14px;
}

.pdf-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #fafafa;
  padding: 20px;
  text-align: center;
}

.error-icon {
  margin-bottom: 16px;
}

.error-message {
  margin-bottom: 20px;
  color: #f56c6c;
  font-size: 14px;
  max-width: 80%;
  line-height: 1.5;
}

.pdf-preview {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.pdf-toolbar {
  height: 48px;
  line-height: 48px;
  padding: 0 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 12px;
  justify-content: space-between;
  box-sizing: border-box;
}

.page-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-info {
  color: #666;
  font-size: 14px;
  min-width: 120px;
  text-align: center;
}

.pdf-content {
  flex: 1;
  overflow: auto;
  background-color: #f8f9fa; /* 改为浅灰色背景，便于观察 */
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px 10px;
  box-sizing: border-box;
  min-height: 400px; /* 确保有最小高度 */
  position: relative;
}

.pdf-canvas {
  max-width: 100%;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.15); /* 加深阴影便于观察 */
  border-radius: 4px;
  transition: box-shadow 0.3s ease;
  background-color: white;
  display: block;

  /* 添加临时边框用于调试 */
  border: 2px solid #e0e0e0;
}

.pdf-canvas:hover {
  box-shadow: 0 4px 25px rgba(0, 0, 0, 0.2);
  border-color: #409eff; /* 悬停时显示蓝色边框 */
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .pdf-toolbar {
    flex-wrap: wrap;
    height: auto;
    padding: 8px 16px;
  }
  .page-control {
    width: 100%;
    justify-content: center;
    margin-top: 8px;
  }
}
</style>